export default {
  data() {
    return {
      dialogType: 'detail',
      id: '', //数据id，用于提交数据
      itemData: null, //详情数据
      formData: {},   //表单数据
    }
  },
  created() {
  },
  watch: {
    dialogType: {
      handler(val) {
        // console.log('now mode:', val)
      },
      immediate: true,
    },
  },
  computed: {
    disabled() {
      return this.dialogType === 'detail'
    },
    isAdd() {
      return this.dialogType === 'add'
    }
  },
  methods: {
    async show(dialogType = 'detail', data) {
      if (this.$refs.formGroup && this.$refs.formGroup.editMode) {
        this.$refs.formGroup.editMode = dialogType;
      }

      this.dialogType = dialogType;
      this.initFormData && this.initFormData(this.dialogType,data);

      if (dialogType !== 'add' && data) {
        this.getDetail && this.getDetail(data);

        if (dialogType === 'detail') {
          this.$refs.formGroup && (this.$refs.formGroup.detailMode = true);
        }
      }

      this.$refs.detailDialog.show(dialogType);
      this.showExpHandle && this.showExpHandle(data);
    },

    /**
     * 对话框确认按钮响应
     * */
    handleConfirm() {
      let data = this.$refs.formGroup.checkValue();
      if (!data) {
        return false;
      }
      if (this.checkExpData) {
        data = this.checkExpData(data);
      }
      if (this.dialogType === 'add') {
        this.submitAdd(data)
      } else {
        this.submitEdit(data)
      }
    },

    /**
     * 记录详情数据修改提交成功，触发data-change消息更新列表数据
     */
    submitSuccess() {
      this.$message.success(this.dialogType === 'add' ? '添加成功' : '修改成功');
      this.hide();
      this.$emit('data-change');
    },
    /**
     * 隐藏对话框
     */
    hide() {
      this.$refs.detailDialog.hide();
      this.$emit('dialog-close');
    },
    // 对 async-select 类型的字段自动监听赋值
    asyncSelectListener(formData, changeData) {
      let fieldsArray = [];

      for (let key in formData) {
        if (formData[key].type === 'async-select') {
          fieldsArray.push(key);
        }
      }

      fieldsArray.forEach(field => {
        if (changeData && changeData.prop === field) {
          console.log(`set ${field} value to:`, changeData.value);
          formData[field].value = changeData.value || '';
        }
      });
    },
  }
}
